package com.approval.approvalapp.center.acitivty;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.approval.approvalapp.MyAppliaction;
import com.approval.approvalapp.R;
import com.approval.approvalapp.center.adapter.ThingsCensusAdapter;
import com.approval.approvalapp.center.adapter.ThingsCensusItemAdapter;
import com.approval.approvalapp.center.bean.ThingsCensusBean;
import com.approval.approvalapp.center.bean.ThingsCensusItemBean;
import com.approval.approvalapp.util.SpUtil;
import com.approval.approvalapp.util.base.BaseActivity;
import com.approval.approvalapp.util.net.NetRequsetUtil;
import com.approval.approvalapp.util.net.interfacepac.NetDownResponse;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.IDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.MPPointF;
import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

//事项统计
public class ThingsCensusActivity extends BaseActivity implements AppBarLayout.OnOffsetChangedListener {

    @Bind(R.id.tv1)
    TextView tv1;
    @Bind(R.id.tv2)
    TextView tv2;
    @Bind(R.id.tv4)
    TextView tv4;
    @Bind(R.id.tv5)
    TextView tv5;
    @Bind(R.id.tv6)
    TextView tv6;
    private List<ThingsCensusBean.ListBean> qs_list = new ArrayList<>();
    private List<ThingsCensusBean.ListBean> list = new ArrayList<>();
    private ProgressDialog progressDialog;

    public static void goInto(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, ThingsCensusActivity.class);
        context.startActivity(intent);
    }

    @Bind(R.id.back_iv)
    ImageView backIv;
    @Bind(R.id.titleTv1)
    TextView titleTv1;
    @Bind(R.id.view_shengji)
    View viewShengji;
    @Bind(R.id.rl_shengji)
    RelativeLayout rlShengji;
    @Bind(R.id.view_all_province)
    View viewAllProvince;
    @Bind(R.id.rl_all_province)
    RelativeLayout rlAllProvince;
    @Bind(R.id.tv_shengji)
    TextView tvShengji;
    @Bind(R.id.tv_allprovince)
    TextView tvAllprovince;
    @Bind(R.id.pieChart)
    PieChart pieChart;
    @Bind(R.id.piecolortv)
    TextView piecolortv;
    @Bind(R.id.pjmctv)
    TextView pjmctv;
    @Bind(R.id.pjnumtv)
    TextView pjnumtv;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.collapsing_toolbar)
    CollapsingToolbarLayout collapsingToolbar;
    @Bind(R.id.appbar)
    AppBarLayout appbar;
    @Bind(R.id.recyclerview)
    XRecyclerView mRecyclerView;
    @Bind(R.id.main_content)
    CoordinatorLayout mainContent;
//    @Bind(R.id.swipeRefreshLayout)
//    SwipeRefreshLayout swipeRefreshLayout;
    @Bind(R.id.sbjsxzs)
    TextView sbjsxzs;
    private LinearLayoutManager mLayoutManager;
    private ThingsCensusAdapter mAdapter;
    List<ThingsCensusBean.ListBean> mList = new ArrayList<>();
    private ThingsCensusBean provinceCensusBean;
    private boolean isAllsheng;

    @Override
    public int getLayoutId() {
        return R.layout.things_census_layout;
    }

    @Override
    public void initView() {
        sbjsxzs.setVisibility(View.GONE);
        initXR();
    }

    @Override
    public void initData() {
        setShengji();
        ThingsCensusItemAdapter adapter = new ThingsCensusItemAdapter(new ArrayList<ThingsCensusItemBean>(), this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
        getData();
    }

    private void initXR() {
        mLayoutManager = new LinearLayoutManager(this);
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(mLayoutManager);

        mRecyclerView.setPullRefreshEnabled(false);
        mRecyclerView.setLoadingMoreEnabled(false);
//        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
//            @Override
//            public void onRefresh() {
//                new Handler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        mRecyclerView.setNoMore(false);
//                        getData();
//                    }
//                }, 500);
//            }
//        });
        mRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {

            }

            @Override
            public void onLoadMore() {

            }
        });

        appbar.addOnOffsetChangedListener(this);

        mAdapter = new ThingsCensusAdapter(mList, this);
        mRecyclerView.setAdapter(mAdapter);
    }

    public void getData() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在加载");
        progressDialog.show();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("org_code", SpUtil.getString(MyAppliaction.getInstance(), SpUtil.ORG_CODE, "-1"));
        jsonObject.put("region_code", SpUtil.getString(MyAppliaction.getInstance(), SpUtil.REGION_CODE, "-1"));
        NetRequsetUtil.getInstance().netRequestPostJson("v1/user/get_sxlx_num", jsonObject.toString(), new NetDownResponse() {
            public String TAG = getClass().getSimpleName();

            @Override
            public void success(String str) {
                Gson gson = new Gson();
                provinceCensusBean = gson.fromJson(str, ThingsCensusBean.class);

                list = provinceCensusBean.getList();
                qs_list = provinceCensusBean.getQs_list();

                mList.clear();
                mList.addAll(list);
                mAdapter.notifyDataSetChanged();

                mAdapter.setIsallsheng(isAllsheng);

                initPieChart(provinceCensusBean.getQs());
                if (provinceCensusBean != null) {
                    List<ThingsCensusBean.QsBean> provinceCensusBeanSj = provinceCensusBean.getSj();
                    setPieDataCk(provinceCensusBeanSj);

                    piecolortv.setText(provinceCensusBeanSj.get(0).getBfb() + "");
                    pjnumtv.setText(provinceCensusBeanSj.get(0).getNum() + "");
                    pjmctv.setText(provinceCensusBeanSj.get(0).getTitle());
                    pjmctv.setTextColor(Color.parseColor("#4071FF"));
                }
            }

            @Override
            public void errowithresponse(String str) {

            }

            @Override
            public void erro() {

            }

            @Override
            public void finish() {
                if (progressDialog != null) {
                    progressDialog.dismiss();
                }
//                if (swipeRefreshLayout != null) {
//                    swipeRefreshLayout.setRefreshing(false);
//                    mRecyclerView.loadMoreComplete();
//                    if (progressDialog != null) {
//                        progressDialog.dismiss();
//                    }
//                }
            }
        });

    }


    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
//        if (verticalOffset == 0) {
//            swipeRefreshLayout.setEnabled(true);
//        } else {
//            swipeRefreshLayout.setEnabled(false);
//        }

    }

    @OnClick({R.id.back_iv, R.id.rl_shengji, R.id.rl_all_province})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_iv:
                finish();
                break;
            case R.id.rl_shengji:
                setShengji();
                if (provinceCensusBean != null) {
                    List<ThingsCensusBean.QsBean> provinceCensusBeanSj = provinceCensusBean.getSj();
                    setPieDataCk(provinceCensusBeanSj);
                }
                if (provinceCensusBean != null) {
                    List<ThingsCensusBean.QsBean> provinceCensusBeanSj = provinceCensusBean.getSj();
                    piecolortv.setText(provinceCensusBeanSj.get(0).getBfb() + "");
                    pjnumtv.setText(provinceCensusBeanSj.get(0).getNum() + "");
                    pjmctv.setText(provinceCensusBeanSj.get(0).getTitle());
                    pjmctv.setTextColor(Color.parseColor("#4071FF"));
                }
                mList.clear();
                mList.addAll(list);
                mAdapter.notifyDataSetChanged();
                sbjsxzs.setVisibility(View.GONE);
                isAllsheng = false;

                mAdapter.setIsallsheng(isAllsheng);

                tv1.setText("部门名称");
                tv4.setText("可网办率");
                tv5.setText("实际网办率");



                break;
            case R.id.rl_all_province:
                tv1.setText("市级");
                tv4.setText("可网办率");
                tv5.setText("实际网办率");
                sbjsxzs.setVisibility(View.VISIBLE);

                tvAllprovince.setTextColor(Color.parseColor("#1465FD"));
                tvShengji.setTextColor(Color.parseColor("#7D8198"));
                viewAllProvince.setVisibility(View.VISIBLE);
                viewShengji.setVisibility(View.GONE);
                if (provinceCensusBean != null) {
                    setPieDataCk(provinceCensusBean.getQs());
                }
                if (provinceCensusBean != null) {
                    List<ThingsCensusBean.QsBean> provinceCensusBeanSj = provinceCensusBean.getQs();
                    piecolortv.setText(provinceCensusBeanSj.get(0).getBfb() + "");
                    pjnumtv.setText(provinceCensusBeanSj.get(0).getNum() + "");
                    pjmctv.setText(provinceCensusBeanSj.get(0).getTitle());
                    pjmctv.setTextColor(Color.parseColor("#4071FF"));
                }
                mList.clear();
                mList.addAll(qs_list);
                mAdapter.notifyDataSetChanged();
                isAllsheng = true;
                mAdapter.setIsallsheng(isAllsheng);
                break;
        }
    }

    private void setShengji() {
        tvAllprovince.setTextColor(Color.parseColor("#7D8198"));
        tvShengji.setTextColor(Color.parseColor("#1465FD"));
        viewShengji.setVisibility(View.VISIBLE);
        viewAllProvince.setVisibility(View.GONE);
    }

    private void initPieChart(final List<ThingsCensusBean.QsBean> beanQs) {

        pieChart.setUsePercentValues(true);
        pieChart.getDescription().setEnabled(false);
        pieChart.setExtraOffsets(0, 0, 0, 0);
        pieChart.setCenterText("");//中间的文字
        pieChart.setDrawHoleEnabled(true);//中间的洞
        pieChart.setHoleColor(Color.WHITE);
        pieChart.setTransparentCircleColor(Color.WHITE);
        pieChart.setTransparentCircleAlpha(110);
        pieChart.setHoleRadius(78f);
        pieChart.setTransparentCircleRadius(61f);
        pieChart.setDrawCenterText(true);//是否显示中间文字
        pieChart.setRotationAngle(0);
        pieChart.setDrawSliceText(false);//是否显示文字
        pieChart.setRotationEnabled(true);
        pieChart.setHighlightPerTapEnabled(true);
        pieChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, Highlight h) {
                int x = (int) h.getX();

                    piecolortv.setText(beanQs.get(x).getBfb() + "");
                    pjnumtv.setText(beanQs.get(x).getNum() + "");
                    pjmctv.setText(beanQs.get(x).getTitle());
                    switch (x) {
                        case 0:
                            //行政许可
                            pjmctv.setTextColor(Color.parseColor("#4071FF"));
                            break;
                        case 1:
//                            pjmctv.setText("行政检查");
                            pjmctv.setTextColor(Color.parseColor("#F8AF35"));
                            break;
                        case 2:
//                            pjmctv.setText("行政处罚");
                            pjmctv.setTextColor(Color.parseColor("#3BD5FF"));
                            break;
                        case 3:
//                            pjmctv.setText("行政征收");
                            pjmctv.setTextColor(Color.parseColor("#FFD649"));
                            break;
                        case 4:
//                            pjmctv.setText("行政确认");
                            pjmctv.setTextColor(Color.parseColor("#EC376F"));
                            break;
                        case 5:
//                            pjmctv.setText("行政奖励");
                            pjmctv.setTextColor(Color.parseColor("#8942FF"));
                            break;
                        case 6:
//                            pjmctv.setText("行政强制");
                            pjmctv.setTextColor(Color.parseColor("#C11F2E"));
                            break;
                        case 7:
//                            pjmctv.setText("公共服务");
                            pjmctv.setTextColor(Color.parseColor("#5840FF"));
                            break;
                        case 8:
//                            pjmctv.setText("行政给付");
                            pjmctv.setTextColor(Color.parseColor("#DE463A"));
                            break;
                        case 9:
//                            pjmctv.setText("行政裁决");
                            pjmctv.setTextColor(Color.parseColor("#5793F3"));
                            break;
                    }

            }

            @Override
            public void onNothingSelected() {

            }
        });
        Legend legend = pieChart.getLegend();
        legend.setEnabled(false);
    }

    public static final int[] VORDIPLOM_COLORS1 = {
            Color.parseColor("#4071FF"),
            Color.parseColor("#F8AF35"),
            Color.parseColor("#3BD5FF"),
            Color.parseColor("#FFD649"),
            Color.parseColor("#EC376F"),
            Color.parseColor("#8942FF"),
            Color.parseColor("#C11F2E"),
            Color.parseColor("#5840FF"),
            Color.parseColor("#DE463A"),
            Color.parseColor("#5793F3")
    };

    private void setPieDataCk(List<ThingsCensusBean.QsBean> beanQs) {

        ArrayList<PieEntry> entries = new ArrayList<PieEntry>();

        // NOTE: The order of the entries when being added to the entries array determines their position around the center of
        // the chart.
        for (ThingsCensusBean.QsBean beanQ : beanQs) {
            entries.add(new PieEntry((float) (Integer.valueOf(beanQ.getNum())),
                    beanQ.getTitle(),
                    getResources().getDrawable(R.drawable.star)));
        }

        PieDataSet dataSet = new PieDataSet(entries, "");

        dataSet.setDrawIcons(false);

        dataSet.setSliceSpace(3f);
        dataSet.setIconsOffset(new MPPointF(0, 40));
        dataSet.setSelectionShift(5f);

        ArrayList<Integer> colors = new ArrayList<Integer>();

        for (int c : VORDIPLOM_COLORS1)
            colors.add(c);

        dataSet.setColors(colors);
        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(11f);
        data.setValueTextColor(Color.WHITE);
        pieChart.setData(data);
        pieChart.highlightValues(null);
        for (IDataSet<?> set : pieChart.getData().getDataSets()) {
            set.setDrawValues(false);
        }

        pieChart.invalidate();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
